package com.useeinfo.oa.open.api.inspection;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.inspection.biz.FacilityInspectionSnapBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionOrderBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionWorkLogBiz;
import com.useeinfo.oa.modules.inspection.entity.FacilityInspectionSnap;
import com.useeinfo.oa.modules.inspection.entity.InspectionOrder;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @auther: bin.liu
 * @Date: 2019/1/11 17:27
 * @Description: 巡检工单api
 */
@RestController
@RequestMapping("/api/inspectionOrder")
public class InspectionOrderAPI {
    @Autowired
    private InspectionWorkLogBiz inspectionWorkLogBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private InspectionOrderBiz inspectionOrderBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityInspectionSnapBiz facilityInspectionSnapBiz;

    /**
     * 添加/修改工作日志
     */
    @RequestMapping("/addOrUpdateLog")
    public ResultDto addOrUpdateLog(String logId, String workLogCatId, String workLogLevelId, String workContent, String photos, String inspectionOrderId) {
        return inspectionWorkLogBiz.addOrUpdateLog(logId, workLogCatId, workLogLevelId, workContent, photos, inspectionOrderId);
    }

    /**
     * 工作日志列表
     */
    @RequestMapping("/inspectionWorkLogList")
    public ResultDto inspectionWorkLogList(String pageIndex, String pageSize, String inspectionOrderId) {
        return inspectionWorkLogBiz.inspectionWorkLogList(pageIndex, pageSize, inspectionOrderId);
    }

    /**
     * 工作日志详情
     */
    @RequestMapping("/inspectionWorkLogDetail")
    public ResultDto inspectionWorkLogDetail(String inspectionWorkLogId) {
        return inspectionWorkLogBiz.inspectionWorkLogDetail(inspectionWorkLogId);
    }

    /**
     * 关注/取消关注
     *
     * @param inspectionOrderId
     * @param type
     * @return
     */
    @RequestMapping("/focus")
    public ResultDto focus(String inspectionOrderId, Boolean type) {
        return inspectionOrderBiz.focus(inspectionOrderId, type);
    }

    /**
     * 参与人列表
     */
    @RequestMapping("/partnerList")
    @ResponseBody
    public ResultDto partnerList(String id) {
        return inspectionOrderBiz.partnerList(id);
    }

    /**
     * 添加参与人
     */
    @RequestMapping("/addPartner")
    @ResponseBody
    public ResultDto addPartner(String inspectionOrderId, String partnerArray) {
        return inspectionOrderBiz.addPartner(inspectionOrderId, partnerArray);
    }

    /**
     * 移除参与人
     */
    @RequestMapping("/removePartner")
    @ResponseBody
    public ResultDto removePartner(String id) {
        return inspectionOrderBiz.removePartner(id);
    }

    /**
     * 参与人详情
     *
     * @param id
     * @param userId
     * @param tag
     * @return
     */
    @RequestMapping("/partnerDetail")
    @ResponseBody
    public ResultDto partnerDetail(String id, String userId, String tag) {
        return inspectionOrderBiz.partnerDetail(id, userId, tag);
    }

    /**
     * 添加备注
     */
    @RequestMapping("/addRemark")
    @ResponseBody
    public ResultDto addRemark(String contentId, String question, String measure, String remark) {
        return inspectionOrderBiz.addRemark(contentId, question, measure, remark,null);
    }

    /**
     * 查询备注备注
     */
    @RequestMapping("/getRemark")
    @ResponseBody
    public ResultDto getRemark(String contentId) {
        return inspectionOrderBiz.getRemark(contentId);
    }

    /**
     * 添加参与人查看更多
     */
    @RequestMapping("/partnerAddMore")
    @ResponseBody
    public ResultDto partnerAddMore(String contentArray, String inspectionOrderId) {
        return inspectionOrderBiz.partnerAddMore(contentArray, inspectionOrderId);
    }
    /**
     * 工作流程
     * @param inspectionOrderId
     * @return
     */
    @RequestMapping("/workProgress")
    @ResponseBody
    public ResultDto workProgress(String inspectionOrderId) {
        return inspectionOrderBiz.workProgress(inspectionOrderId);
    }

    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public ResultDto detail(String id) {
        return inspectionOrderBiz.detail(id);
    }

    /**
     * 查询列表接口
     *
     * @param status    状态 0 待接单，1进行中 2 审核中 3 完成 4批量审核 5批量转单
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/list")
    public ResultDto list(String status, String pageIndex, String pageSize, String searchParam) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        return inspectionOrderBiz.list(status, pageIndex,pageSize, systemUser, enterprise, searchParam,"");
    }

    /**
     * 接单
     *
     * @param inspectionOrderId
     * @return
     */
    @RequestMapping("/receive")
    public ResultDto receive(String inspectionOrderId) {
        return inspectionOrderBiz.receive(inspectionOrderId);
    }

    /**
     * 到场
     */
    @RequestMapping("/present")
    public ResultDto present(String inspectionOrderId, String longitude, String latitude) {
        return inspectionOrderBiz.present(inspectionOrderId, longitude, latitude);
    }

    /**
     * 上传接口
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResultDto upload(MultipartFile file, String type) {
        return inspectionOrderBiz.upload(file, type);
    }

    /**
     * 批量上传接口
     */
    @RequestMapping("/uploads")
    @ResponseBody
    public ResultDto uploads(@RequestParam(value = "file", required = false) MultipartFile[] file, String type,String moduleType) {
        return inspectionOrderBiz.uploads(file, type,moduleType);
    }

    /**
     * 异常报修
     */
    @RequestMapping("/addRepair")
    @ResponseBody
    public ResultDto addRepair(String inspectionCode, String repairCode,String contentId) {
        return inspectionOrderBiz.addRepair(inspectionCode, repairCode,contentId,false);
    }

    /**
     * 巡检报修
     */
    @RequestMapping("/addInspectionRepair")
    @ResponseBody
    public ResultDto addInspectionRepair(String inspectionCode, String repairCode,String contentId){
        return inspectionOrderBiz.addRepair(inspectionCode, repairCode,contentId,true);
    }


    /**
     * 关联维修单列表
     */
    @RequestMapping("/relateRepairOrder")
    @ResponseBody
    public ResultDto relateRepairOrder(String inspectionCode) {
        return inspectionOrderBiz.relateRepairOrder(inspectionCode);
    }

    /**
     * 设备巡检记录列表
     */
    @RequestMapping(value = "/inspectionOrderListByFacility")
    public ResultDto inspectionOrderListByFacility(@RequestParam(value = "facilityId", required = false) String facilityId,
                                                   @RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                                   @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                                   HttpServletRequest request){
        JSONObject data = new JSONObject();
        JSONArray rows = new JSONArray();
        data.put("rows",rows);
        data.put("records",0);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.success(data);
        }
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(facilityId));
        if(facility==null){
            return ResultUtil.success(data);
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("facilityId",facilityId);
        List<FacilityInspectionSnap> facilityInspectionSnapList = facilityInspectionSnapBiz.findList(queryParam);
        String orderIds = "";
        if(CollectionUtils.isNotEmpty(facilityInspectionSnapList)){
            for(FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList){
                if(facilityInspectionSnap.getInspectionOrder()!=null&&!facilityInspectionSnap.getInspectionOrder().isDeleteStatus()){
                    if(StringUtils.isBlank(orderIds)){
                        orderIds += facilityInspectionSnap.getInspectionOrder().getId()+"";
                    }else{
                        orderIds +=","+facilityInspectionSnap.getInspectionOrder().getId();
                    }
                }
            }
        }
        if(StringUtils.isNotBlank(orderIds)){
            QueryParam queryParam1 = new QueryParam(pageIndexParam,pageSizeParam);
            queryParam1.getSqlMap().put("idIn",orderIds);
            List<InspectionOrder> inspectionOrderList = inspectionOrderBiz.findList(queryParam1);
            if(CollectionUtils.isNotEmpty(inspectionOrderList)){
                for(InspectionOrder inspectionOrder : inspectionOrderList){
                    JSONObject jsonObject = inspectionOrder.toJSONObject();
                    JSONArray tags = new JSONArray();
                    JSONObject tag;
                    if (inspectionOrder.isOrderType()) {
                        tag = new JSONObject();
                        tag.put("color", "blue");
                        tag.put("name", "一次性");
                        tags.add(tag);
                    } else {
                        tag = new JSONObject();
                        tag.put("name", "周期性");
                        tag.put("color", "blue");
                        tags.add(tag);
                    }
                    if (null != inspectionOrder.getOrderAssignTypeEnum()) {
                        tag = new JSONObject();
                        tag.put("color", "blue");
                        tag.put("name", "被指派");
                        tags.add(tag);
                    }
                    /*****判断是否逾期和异常******/
                    if (!inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_PULISHING") && !inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_TAKING")) {
                        if (inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_PRESENCE") || inspectionOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
                            if (inspectionOrder.getDelayRealTime().before(new Date())) {
                                tag = new JSONObject();
                                tag.put("color", "blue");
                                tag.put("name", "逾期");
                                tags.add(tag);
                            }
                        } else if (inspectionOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING") || inspectionOrder.getOrderStatusEnum().getCode().equals("COMPLETED")) {
                            if (null != inspectionOrder.getFinishTime()) {
                                if (inspectionOrder.getDelayRealTime().before(inspectionOrder.getFinishTime())) {
                                    tag = new JSONObject();
                                    tag.put("color", "blue");
                                    tag.put("name", "逾期");
                                    tags.add(tag);
                                }
                            }
                        }
                        if (inspectionOrder.isAbnormal()) {
                            tag = new JSONObject();
                            tag.put("color", "red");
                            tag.put("name", "异常");
                            tags.add(tag);
                        }
                    }
                    jsonObject.put("tags", tags);
                    rows.add(jsonObject);
                }
                data.put("rows",rows);
            }
            QueryParam queryParam2 = new QueryParam();
            queryParam2.getSqlMap().put("idIn",orderIds);
            List<InspectionOrder> inspectionOrderList2 = inspectionOrderBiz.findList(queryParam2);
            if(CollectionUtils.isNotEmpty(inspectionOrderList2)){
                data.put("records",inspectionOrderList2.size());
            }
        }
        return  ResultUtil.success(data);
    }

    /**
     * 设备的维保记录
     * @param deviceId
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping("/deviceKeeping")
    public ResultDto deviceKeep(String deviceId,String pageIndex,String pageSize){
        String hql = "select obj from InspectionOrder obj where exists( select fm from FacilityInspectionSnap fm where fm.inspectionOrder.id=obj.id and obj.deleteStatus = false and" +
                "fm.facilityId ="+StringConverters.null2Long(deviceId)+") ";
        List<InspectionOrder>inspectionOrderList = inspectionOrderBiz.hqlExcute(hql,new QueryParam(pageIndex,pageSize));
        JSONArray jsonArray = new JSONArray();
        for(InspectionOrder inspectionOrder:inspectionOrderList){
            jsonArray.add(inspectionOrder.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }


    /**
     * 查看工作内容（设备和工艺）接口
     */
    @RequestMapping("/getFacilityAndTechnology")
    @ResponseBody
    public ResultDto getFacilityAndTechnology(String facilityId,String inspectionTechnologyId) {
        return inspectionOrderBiz.getFacilityAndTechnology(facilityId,inspectionTechnologyId);
    }


}
